package com.mikao.service.impl;

import com.mikao.dao.UserDao;
import com.mikao.dto.bo.ReqDataTableDto;
import com.mikao.dto.vo.RspDataTableDto;
import com.mikao.entity.User;
import com.mikao.service.UserService;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.persistence.criteria.Predicate;
import java.util.ArrayList;
import java.util.List;

/**
 * @author kenny
 */
@Service
public class UserServiceImpl implements UserService {

    private UserDao userDao;

    public UserServiceImpl(UserDao userDao) {
        this.userDao = userDao;
    }

    @Override
    public RspDataTableDto<User> userList(ReqDataTableDto dataTableDTO, String nameOrMobile) {
        PageRequest pageRequest = new PageRequest(dataTableDTO.getPage(), dataTableDTO.getLength(),
                new Sort(Sort.Direction.DESC, "createTime"));
        Page<User> page = userDao.findAll((root, criteriaQuery, criteriaBuilder) -> {
            List<Predicate> predicates = new ArrayList<>();
            if (StringUtils.hasText(nameOrMobile)) {
                Predicate p1 = criteriaBuilder.like(root.get("name").as(String.class), "%" + nameOrMobile + "%");
                Predicate p2 = criteriaBuilder.like(root.get("phone").as(String.class), "%" + nameOrMobile + "%");
                predicates.add(criteriaBuilder.or(p1, p2));
            }
            return criteriaBuilder.and(predicates.toArray(new Predicate[predicates.size()]));
        }, pageRequest);

        return new RspDataTableDto<>(dataTableDTO.getDraw(), page.getTotalElements(), page.getContent());
    }
}
